import { mapState } from 'vuex'
import store from "@/store"

// 尝试将用户在根目录中的store/index.js的vuex的state变量，全部加载到全局变量中
let $uStoreKey = [];
try{
	$uStoreKey = store.state ? Object.keys(store.state) : [];
}catch(e){
	
}

module.exports = {
	beforeCreate() {
		// 将vuex方法挂在到$u中
		// 使用方法为：如果要修改vuex的state中的user.name变量为"史诗" => this.$u.vuex('user.name', '史诗')
		// 如果要修改vuex的state的version变量为1.0.1 => this.$u.vuex('version', '1.0.1')
		this.$u.vuex = (name, value) => {
			this.$store.commit('$uStore', {
				name,value
			})
		}
		this.$u.addQuantity = (product) => {
			
			let cart = this.$store.state.vuex_cart
			
			// 判断购物车中是否已存在该商品
			let exist = cart.rows.find(item => item.id === product.id)
			if (exist) {
				// 如果已存在，则数量累加
				exist.quantity += 1
			} else {
				// 如果不存在，添加到购物车
				// 确保有quantity字段
				let newProduct = { ...product }
				if (typeof newProduct.quantity !== 'number') {
					newProduct.quantity = 1
				}
				cart.rows.push(newProduct)
			}
			cart.count = cart.rows.reduce((sum, item) => sum + item.quantity, 0)
			cart.total = cart.rows.reduce((total, item) => total + item.price * item.quantity, 0);
			// 保证total保留两位小数
			cart.total = Number(cart.total.toFixed(2));
			this.$u.api.merchant.addCart(cart)
			this.$u.vuex('vuex_cart', cart)
		}
		this.$u.removeCart = (product) => {
			let cart = this.$store.state.vuex_cart
			cart.rows = cart.rows.filter(item => item.id !== product.id)
			cart.count = cart.rows.reduce((sum, item) => sum + item.quantity, 0)
			cart.total = cart.rows.reduce((total, item) => total + item.price * item.quantity, 0);
			this.$u.vuex('vuex_cart', cart)
		}
		this.$u.clearCart = () => {
			let cart = this.$store.state.vuex_cart
			cart.rows = []
			cart.count = 0
			cart.total = 0
			this.$u.api.merchant.clearCart()
			this.$u.vuex('vuex_cart', cart)
		}

		this.$u.subQuantity = (product) => {
			let cart = this.$store.state.vuex_cart
			if(!Array.isArray(cart.rows)){
				cart.rows = [];
			}
			cart.rows.find(item => item.id === product.id).quantity--;
			// 如果商品数量减到0，则从购物车中移除该商品
			let item = cart.rows.find(item => item.id === product.id);
			if(item.quantity <= 0){

				cart.rows = cart.rows.filter(i => i.id !== product.id);
			}
			cart.count = cart.rows.reduce((sum, item) => sum + item.quantity, 0)
			cart.total = cart.rows.reduce((total, item) => total + item.price * item.quantity, 0);
			// 保证total保留两位小数
			cart.total = Number(cart.total.toFixed(2));
			this.$u.api.merchant.addCart(cart)
			this.$u.vuex('vuex_cart', cart)
		}
		
	},
	computed: {
		// 将vuex的state中的所有变量，解构到全局混入的mixin中
		...mapState($uStoreKey)
	}
}